package br.sc.senai.model.bd;

import br.sc.senai.model.util.Sup;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jefferson_augusto
 */
public class CriacaoBanco {
    
    private static final String SQL_TABELA_USUARIO = "create table if not exists usuario ("
            + "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,"
            + "login varchar(50) not null,"
            + "senha varchar(100) not null,"
            + "tipo int not null)";
    
    private static final String SQL_INSERT_UER_ADMIN = "insert into usuario (login, senha, tipo)"
            + "values"
            + "('Admin', 'rx08ndTjy1jZzRlG01q3Ng==', 0);";
    
    private static final String SQL_TABELA_CONTA = "create table if not exists conta ("
            + "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,"
            + "id_usuario int not null,"
            + "nome varchar(30) not null,"
            + "valorTotal double not null,"
            + "numeroParcelas int not null,"
            + "dataVencimento date not null,"
            + "descricao varchar(60),"
            + "status int not null,"
            + "CONSTRAINT `FK_CONTA_USUARIO` FOREIGN KEY (id_usuario) REFERENCES usuario(id));";
    
    CriacaoBanco() {
        criarTabelas();
    }

    public static void criarTabelas() {
        Connection mConnection = null;
        try {

            mConnection = Conexao.conecta();

            Statement stm = mConnection.createStatement();
            stm.executeUpdate(SQL_TABELA_USUARIO);
            System.out.println("Executado sql: SQL_TABELA_USUARIO");
            stm.executeUpdate(String.format(SQL_INSERT_UER_ADMIN, Sup.encrypt("Admin")));
            System.out.println("Executado sql: SQL_INSERT_UER_ADMIN");
            stm.executeUpdate(SQL_TABELA_CONTA);
            System.out.println("Executado sql: SQL_TABELA_CONTA");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
            System.out.println(e.getCause());
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                Conexao.desconectar(mConnection);
            } catch (SQLException ex) {
                Logger.getLogger(CriacaoBanco.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(CriacaoBanco.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String[] args) {
        try {
            Conexao.criarBanco("GerenciaConta");
            criarTabelas();
        } catch (Exception ex) {
            Logger.getLogger(CriacaoBanco.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
